package com.flainsky.nirvanaplayer;

import java.util.ArrayList;
import java.util.List;

import com.flainsky.nirvanaplayer.adpters.RankingAdapter;
import com.flainsky.nirvanaplayer.cache.ImageCache;
import com.flainsky.nirvanaplayer.globe.CheckDevice;
import com.flainsky.nirvanaplayer.globe.DataCollection;
import com.flainsky.nirvanaplayer.globe.DownloadUtils;
import com.flainsky.nirvanaplayer.globe.Env;
import com.flainsky.nirvanaplayer.globe.GlobeCache;
import com.flainsky.nirvanaplayer.globe.DownloadUtils.DataType;
import com.flainsky.nirvanaplayer.lib.objects.ImageViewData;
import com.flainsky.nirvanaplayer.lib.objects.Movie;
import com.flainsky.nirvanaplayer.views.MovieInfoRelativeLayout;
import com.flainsky.nirvanaplayer.webservice.FlaParameter;
import com.flainsky.nirvanaplayer.webservice.FlaWebservice;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
//import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SMainActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */	
	private final static int MAX_OF_TOP_MOVIE = 8;
	TextView tv_main;
	TextView tv_live;
	TextView tv_movie;
	TextView tv_tv;
	TextView tv_show;
	TextView tv_news;
	ListView lv_ranking;
	MovieInfoRelativeLayout[] movieInfo;
	
	ImageView largeImage;		//超大图
	ImageView trBgImage;		//右上背景图
	ImageView[] circleImage;	//8个圆圈
	
	TextView tv_hot_title;
	TextView tv_hot_info;
	
	ProgressDialog pdialog;	//进度条
	
	//singletons
	DataCollection datas;	//数据单例
	FlaWebservice ws;		//服务单例
	Env env;				//环境变量单例
	float x;
	
	LoadInfoAsyncTask loadingTask;	
	RankingAdapter rAdapter;
	
	boolean loadCache = false;
	
	int numDImages = 0;
	int largeImageNo = 0;
	ImageCache cache;
	
	enum DownloadItemOder{
		first,last,other,large
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.smain);
      
        findViews();
        addListeners();
        init();        
        if(checkDevice())	//有网络连接时，从WebService读取数据
        {
        	loadingDatas();
        }
    }
    
    @Override
	public void onResume()
    {
    	super.onResume();
/*    	if(loadCache)
    	{
    		loadCache = false;
    		LoadCacheAsyncTask loadCacheTask = new LoadCacheAsyncTask();
    		loadCacheTask.execute();
    	}*/
    }
    
    @Override
    public void onPause()
    {
    	super.onPause();
/*    	cache.clear();
    	loadCache = true;*/
    }
    
    private void loadingDatas()
    {
    	loadingTask = new LoadInfoAsyncTask();
    	loadingTask.execute();
    }
    
    private boolean checkDevice()
    {
    	return CheckDevice.checkNetWorkStatus(SMainActivity.this);
    	//检查广域网连接
    	/*String url = this.getString(R.string.test_connect);
    	CheckDevice.checkURL(MainActivity.this,url);*/
    }
    
    private void init()
    {
    	//启用android main thread webservice
    	//不过我给写到Task里了，这里单纯方便以后人开发
    	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    	.detectDiskReads()
    	.detectDiskWrites()
    	.detectNetwork()   // or .detectAll() for all detectable problems
    	.penaltyLog()
    	.build());
    	StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
    	.detectLeakedSqlLiteObjects()
    	.detectLeakedClosableObjects()
    	.penaltyLog()
    	.penaltyDeath()
    	.build());
    	
    	Env.makeInstance(SMainActivity.this);
    	FlaWebservice.makeInstance(SMainActivity.this);
    	DataCollection.makeInstance(SMainActivity.this);
    	GlobeCache.makeInstance(SMainActivity.this);
    	cache = GlobeCache.getInstance().getCache();
    	datas = DataCollection.getInstance();
    	ws = FlaWebservice.getInstance();
    	env = Env.getInstance();
    	
    	pdialog = new ProgressDialog(SMainActivity.this);
    	pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
	         public void onClick(DialogInterface dialog, int i) {
	        	 dialog.cancel();
	         }
	    });
    	pdialog.setTitle(R.string.wait);
        pdialog.setCancelable(true);
        pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    }
    
    private void findViews()
    {
    	tv_main = (TextView)findViewById(R.id.mainpage_tv);
        tv_live = (TextView)findViewById(R.id.live_tv);
        tv_movie = (TextView)findViewById(R.id.movie_tv);
        tv_tv = (TextView)findViewById(R.id.tv_tv);
        tv_show = (TextView)findViewById(R.id.show_tv);
        tv_news = (TextView)findViewById(R.id.news_tv);
        lv_ranking = (ListView)findViewById(R.id.main_ranking_lv);
        movieInfo = new MovieInfoRelativeLayout[5];
        movieInfo[0] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info1);
        movieInfo[1] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info2);
        movieInfo[2] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info3);
        movieInfo[3] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info4);
        movieInfo[4] = (MovieInfoRelativeLayout)findViewById(R.id.movie_info5);
        
        circleImage = new ImageView[8];
        circleImage[0] = (ImageView)findViewById(R.id.circle1);
        circleImage[1] = (ImageView)findViewById(R.id.circle2);
        circleImage[2] = (ImageView)findViewById(R.id.circle3);
        circleImage[3] = (ImageView)findViewById(R.id.circle4);
        circleImage[4] = (ImageView)findViewById(R.id.circle5);
        circleImage[5] = (ImageView)findViewById(R.id.circle6);
        circleImage[6] = (ImageView)findViewById(R.id.circle7);
        circleImage[7] = (ImageView)findViewById(R.id.circle8);
        
        largeImage = (ImageView)findViewById(R.id.main_image);
        trBgImage = (ImageView)findViewById(R.id.top_movie_bg_img);
        
        tv_hot_title = (TextView)findViewById(R.id.hot_title);
        tv_hot_info = (TextView)findViewById(R.id.hot_info);
    }
    
    private void addListeners()
    {
    	tv_main.setOnClickListener(this);
    	tv_live.setOnClickListener(this);
    	tv_movie.setOnClickListener(this);
    	tv_tv.setOnClickListener(this);
    	tv_show.setOnClickListener(this);
    	tv_news.setOnClickListener(this);
    	for(int i = 0;i<MAX_OF_TOP_MOVIE;i++)
    	{
    		final int n = i;
            circleImage[n].setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				largeImageNo = n;
    				changeTopMovie(n);
    			}
    		});
    	}
    	largeImage.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if(event.getAction() == MotionEvent.ACTION_DOWN)
				{
					x = event.getX();
				}
				if(event.getAction() == MotionEvent.ACTION_UP)
				{
					if(event.getX()-x>100)
					{
						largeImageNo++;
						if(largeImageNo>=MAX_OF_TOP_MOVIE)
						{
							largeImageNo = 0;
						}
						changeTopMovie(largeImageNo);
					}
					else if(event.getX()-x<-100)
					{
						largeImageNo--;
						if(largeImageNo<=0)
						{
							largeImageNo = MAX_OF_TOP_MOVIE-1;
						}
						changeTopMovie(largeImageNo);
					}
				}
				return true;
			}
		});
    }
    

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId())
		{
		case R.id.mainpage_tv:
			return;
		case R.id.live_tv:
			swichToLiveListPage();
			return;
		case R.id.movie_tv:
			switchToMovieListPage();
			return;
		case R.id.show_tv:
			break;
		}
		
	}
	
	private void switchToMovieListPage()
	{
		Intent intent = new Intent(SMainActivity.this,MovieListActivity.class);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	
	private void swichToLiveListPage()
	{
		Intent intent = new Intent(SMainActivity.this,LiveListActivity.class);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	
	private void fillData()
	{
		//填充排行榜
		rAdapter = new RankingAdapter(SMainActivity.this, datas.getHotList());
		lv_ranking.setAdapter(rAdapter);
		
		//下载数据，今日推荐下载小图，上面下载大小图
		downloadImages();
		
		//填充今日推荐
		List<Movie> todayList = datas.getTodayList();
		int counter = 0;
		for(Movie movie : todayList)
		{
			movieInfo[counter].setTitle(movie.mTitle);
			movieInfo[counter].setRb(movie.mComment);
			counter++;
		}
		
		//填充上面，并启动循环线程
		largeImageNo = 0;
		changeTopMovie(0);
	}
	
	private void downloadImages()
	{
		List<ImageViewData> urls = new ArrayList<ImageViewData>();
		List<ImageViewData> savedUrls = new ArrayList<ImageViewData>();
		int counter = 0;
		for(Movie movie : datas.getTodayList())
		{
			urls.add(new ImageViewData(movie.mSimage,movieInfo[counter++].getImageView()));
		}
		
/*		for(Movie movie : datas.getHotList())
		{
			urls.add(new ImageViewData(movie.mBimage,null));
			urls.add(new ImageViewData(movie.mSimage,null));
		}*/
/*		for(ImageViewData ivd : urls)
		{
			String str = DownloadUtils.getUrlName(ivd.url);
			File file = new File(DownloadUtils.DATA_DIR+str);
			if(file.exists())
			{
				savedUrls.add(ivd);
				if(ivd.iv!=null)
				{
					Bitmap bmp = BitmapFactory.decodeFile(DownloadUtils.DATA_DIR+str);
					ivd.iv.setImageBitmap(bmp);
				}
			}
		}*/
		urls.removeAll(savedUrls);
		numDImages = urls.size();
		counter = 0;
		for(ImageViewData ivd : urls)
		{
			DownloadItemOder order = DownloadItemOder.other;
/*			if(counter == 0)
			{
				order = DownloadItemOder.first;
			}
			if((counter+1)==urls.size())
			{
				order = DownloadItemOder.last;
			}*/
			//pdialog.show();
			DownloadImageAsyncTask dit = new DownloadImageAsyncTask(ivd.url, order, ivd.iv,-1);
			dit.execute();
		}
	}
	
	//数据加载cache
	public class LoadCacheAsyncTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute()
		{
			pdialog.setMessage(SMainActivity.this.getString(R.string.load_data));
	        pdialog.show();
		}
		@Override
		protected Void doInBackground(Void... arg0) {
			//加载大图
			BuffHotMovieImage(datas.getHotList());
			return null;
		}
		@Override
	    protected void onPostExecute(Void result) {
			pdialog.cancel();
		}
		
	}
	
	//数据加载Task
	public class LoadInfoAsyncTask extends AsyncTask<Void, Void, Void> {
		public LoadInfoAsyncTask() {
			// TODO Auto-generated constructor stub			
	        pdialog.setMessage(SMainActivity.this.getString(R.string.load_data));
	        pdialog.show();
		}
		@Override
		protected void onPreExecute()
		{
			//nothing to do now....
		}
		
		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			//---------------在这里从WebService加载数据
			//加载所有地区
			//datas.setAreaList(ws.getStringList(FlaWebservice.AREA_METHOD));
			//加载所有年份（倒序）
			//datas.setYearList(ws.getStringList(FlaWebservice.YEAR_METHOD));
			//加载所有种类
			//datas.setCategoryList(ws.getStringList(FlaWebservice.CATEGORY_METHOD));
			
			List<FlaParameter> paras = new ArrayList<FlaParameter>();
			paras.add(new FlaParameter("count",String.valueOf(5)));
			datas.setTodayList(ws.getMovieList(FlaWebservice.MOVIE_NEWS_METHOD, paras));
			
			List<FlaParameter> paras2 = new ArrayList<FlaParameter>();
			paras2.add(new FlaParameter("count",String.valueOf(10)));
			datas.setHotList(ws.getMovieList(FlaWebservice.MOVIE_POPULAR_METHOD, paras2));
			
			List<FlaParameter> paras3 = new ArrayList<FlaParameter>();
			paras3.add(new FlaParameter("count",String.valueOf(8)));
			datas.setRankingList(ws.getMovieList(FlaWebservice.MOVIE_TIMES_METHOD, paras3));
			
			//加载大图
			BuffHotMovieImage(datas.getHotList());
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void result) {
			pdialog.cancel();
			fillData();
		}
	}
	
	//图片下载Task
	public class DownloadImageAsyncTask extends AsyncTask<Void, Void, Void> {

		String mUrl;
		DownloadItemOder mOrder;
		ImageView mIv;
		int mId;
		boolean isFinish = false;
		boolean isNotExit = false;
		public DownloadImageAsyncTask(String url,DownloadItemOder order,ImageView iv,int id)
		{
			mUrl = url;
			mOrder = order;
			mIv = iv;
			mId = id;
		}
		@Override
		protected void onPreExecute()
		{
			if(mOrder == DownloadItemOder.large)
			{
				if(mId != largeImageNo)
				{
					isFinish = true;
				}
			}
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if(!isFinish)
			{
				isNotExit = !DownloadUtils.downloadFile(SMainActivity.this,mUrl,DownloadUtils.DataType.image);
			}
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void result) {
			if(mIv!=null&&!isNotExit)
			{
				if(mOrder == DownloadItemOder.large)
				{
					if(mId != largeImageNo)
					{
						isFinish = true;
						if(pdialog!=null&&pdialog.isShowing())
						{
							pdialog.cancel();
						}
					}
				}
				if(isFinish)return;
				String str = DownloadUtils.getUrlName(mUrl);
				String path = DownloadUtils.getDataParentPath(DataType.image)+str;
				//Options op = new Options();
				Bitmap bmp = BitmapFactory.decodeFile(path);
				mIv.setImageBitmap(bmp);
			}
			if(isNotExit)
			{
				Toast.makeText(SMainActivity.this, mUrl+" file not exits in server!",Toast.LENGTH_LONG).show();
				return;
			}
			if(pdialog!=null&&pdialog.isShowing())
			{
				pdialog.cancel();
			}
		}
	}
	
	private void BuffHotMovieImage(List<Movie> list)
	{
		for(Movie movie:list)
		{
			DownloadUtils.downloadFile(SMainActivity.this,movie.mBimage,DownloadUtils.DataType.image);
			DownloadUtils.downloadFile(SMainActivity.this,movie.mSimage,DownloadUtils.DataType.image);
			String bImage = DownloadUtils.getDataParentPath(DataType.image)+DownloadUtils.getUrlName(movie.mBimage);
			String sImage = DownloadUtils.getDataParentPath(DataType.image)+DownloadUtils.getUrlName(movie.mSimage);
			/*Options opt = new Options();
			opt.inSampleSize = 4;*/
			Bitmap bBmp = BitmapFactory.decodeFile(bImage);
			Bitmap sBmp = BitmapFactory.decodeFile(sImage);
			cache.put(movie.mId*100, sBmp);
			cache.put(movie.mId, bBmp);
			//Log.d("cache",String.valueOf(cache.size()));
			//Log.d("cache", "put "+movie.mBimage);
		}
	}
	
	private void changeTopMovie(int position)
	{
		for(int i = 0;i<MAX_OF_TOP_MOVIE;i++)
		{
			circleImage[i].setImageResource(R.drawable.circle2);
		}
		circleImage[position].setImageResource(R.drawable.circle1);
		Movie movie = datas.getRankingList().get(position);
		tv_hot_title.setText(movie.mTitle);
		tv_hot_info.setText(movie.mIntro);
/*		DownloadImageAsyncTask dat1 = new DownloadImageAsyncTask(movie.mBimage, DownloadItemOder.other, largeImage);
		DownloadImageAsyncTask dat2 = new DownloadImageAsyncTask(movie.mSimage, DownloadItemOder.other, trBgImage);
		dat1.execute();
		dat2.execute();*/
		if(cache.containsKey(movie.mId))
		{
			//Log.d("cache", "has large");
			Bitmap bmp = cache.get(movie.mId);
			largeImage.setImageBitmap(bmp);
			/*DownloadImageAsyncTask dat1 = new DownloadImageAsyncTask(movie.mBimage, DownloadItemOder.large, largeImage,position);
			dat1.execute();*/
		}
		else
		{
			pdialog.show();
			//Log.d("cache",String.valueOf(cache.size()));
			largeImage.setImageResource(R.drawable.loading);
			DownloadImageAsyncTask dat1 = new DownloadImageAsyncTask(movie.mBimage, DownloadItemOder.large, largeImage,movie.mId);
			dat1.execute();
		}
		if(cache.containsKey(movie.mId*GlobeCache.MULTIPLE_OF_SMALL))
		{
			//Log.d("cache", "has small");
			trBgImage.setImageBitmap(cache.get(movie.mId*GlobeCache.MULTIPLE_OF_SMALL));
		}
		else
		{
			trBgImage.setImageResource(R.drawable.loading);
			DownloadImageAsyncTask dat2 = new DownloadImageAsyncTask(movie.mSimage, DownloadItemOder.other, trBgImage,movie.mId*GlobeCache.MULTIPLE_OF_SMALL);
			dat2.execute();
		}
	}
}